<template>
	<baseDialog ref="dialogRef" :title="dialogTitle" width="600px" @confirm="handleSubmit" @close="handleClose">
		<el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
            <el-form-item label="上级名称：" prop="pid">
				<div class="w-80">
					<el-input v-model="formData.parent_name" placeholder="请输入上级名称" clearable disabled />
				</div>
			</el-form-item>
			<el-form-item label="区域名称：" prop="name">
				<div class="w-80">
					<el-input v-model="formData.name" placeholder="请输入区域名称" clearable />
				</div>
			</el-form-item>
            <el-form-item label="区域编码：" prop="code">
				<div class="w-80">
					<el-input v-model="formData.code" placeholder="请输入区域编码" clearable />
				</div>
			</el-form-item>
		</el-form>
	</baseDialog>
</template>

<script setup lang="ts" name="areaEdit">
import { ref, shallowRef, reactive, computed, onMounted, toRaw } from 'vue';
import type { FormInstance } from 'element-plus';
import { areaDetail,areaAdd,areaEdit } from '/@/api/setting/area';

const dialogRef = ref(null);

const dialogType = ref('add');

const dialogTitle = computed(() => {
	return dialogType.value == 'add' ? '添加区域' : '编辑区域';
});

const emit = defineEmits(['submit', 'close']);

const formRef = shallowRef<FormInstance>();

const formData = reactive({
	id: 0,
	name: '',
	pid: 0,
    parent_name: '中国',
    code: "",
    level: 0
});

const rules = reactive({
	name: [{ required: true, message: '请输入区域名称', trigger: ['blur'] }],
    code: [{ required: true, message: '请输入区域编码', trigger: ['blur'] }],
});

const setFormPid = async (row: any) => {
    if(row?.id) {
        formData.pid = row.id;
        formData.parent_name = row.name;
        formData.level = (row.level + 1);
    }
};

const handleSubmit = async () => {
	await formRef.value?.validate(async (valid: boolean) => {
		if (!valid) return;
		if(!formData.pid) formData.pid = 0;
		dialogType.value == 'add' ? await areaAdd(formData) : await areaEdit(formData);
		dialogRef.value?.close();
		emit('submit');
	});
};

const setFormData = async (row: any, callback: any) => {
	const data = await areaDetail({
		id: row.id,
	});

	for (const key in formData) {
		if (data[key] != null && data[key] != undefined) {
			formData[key] = data[key];
		}
	}
	callback();
};

const handleClose = () => {
	emit('close');
};

const open = (type = 'add') => {
	dialogType.value = type;
	dialogRef.value?.open();
};

onMounted(() => {

});

defineExpose({
	open,
	setFormData,
	setFormPid,
});
</script>
